<template>
  <div id="cesiumContainer">
    <div class="tech-layer-control" :class="{ expanded: isPanelExpanded }">
      <!-- 控制图标 -->
      <div class="control-icon" @click="togglePanel" v-if="!isPanelExpanded">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M12 2L2 7l10 5 10-5-10-5z"/>
          <path d="M2 17l10 5 10-5"/>
          <path d="M2 12l10 5 10-5"/>
        </svg>
      </div>

      <!-- 控制面板 -->
      <div class="tech-control-panel" v-if="isPanelExpanded">
        <div class="panel-header">
          <h3>图层控制</h3>
          <div class="close-btn" @click="isPanelExpanded = false">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M18 6L6 18M6 6l12 12"/>
            </svg>
          </div>
        </div>

        <!-- 底图切换 -->
        <div class="panel-section" :data-collapsed="!panelSectionStates.basemap">
          <div class="panel-section-header" @click="toggleSection('basemap')">
            <h4>底图类型</h4>
            <svg class="toggle-icon" :class="{ expanded: panelSectionStates.basemap }" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="6 9 12 15 18 9"></polyline>
            </svg>
          </div>
          <div class="tech-button-group">
            <div 
              v-for="basemap in basemapConfig" 
              :key="basemap.id"
              :class="['tech-btn', { active: currentBasemap === basemap.id }]"
              @click="switchBasemap(basemap.id)"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/>
              </svg>
              {{ basemap.name }}
            </div>
          </div>
        </div>

        <!-- 图层管理 -->
        <div class="panel-section" :data-collapsed="!panelSectionStates.layerManagement">
          <div class="panel-section-header" @click="toggleSection('layerManagement')">
            <h4>图层管理</h4>
            <svg class="toggle-icon" :class="{ expanded: panelSectionStates.layerManagement }" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="6 9 12 15 18 9"></polyline>
            </svg>
          </div>
          <div class="tech-checkbox-group">
            <label class="tech-checkbox">
              <input 
                type="checkbox" 
                v-model="annotationLayerVisible"
                @change="toggleAnnotationLayer"
              >
              <span class="checkmark"></span>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                <circle cx="12" cy="12" r="3"/>
              </svg>
              注记图层
            </label>
            <label class="tech-checkbox">
              <input 
                type="checkbox" 
                v-model="terrainEnabled"
                @change="toggleTerrain"
              >
              <span class="checkmark"></span>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/>
              </svg>
              地形显示
            </label>
            <label class="tech-checkbox">
              <input 
                type="checkbox" 
                v-model="scgisLayerVisible"
                @change="toggleScgisLayer"
              >
              <span class="checkmark"></span>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M12 3v18M3 12h18"/>
              </svg>
              SCGIS天地图底图
            </label>
          </div>
        </div>
        
        <!-- WMS/WMTS服务加载 -->
        <div class="panel-section" :data-collapsed="!panelSectionStates.wmtsService">
          <div class="panel-section-header" @click="toggleSection('wmtsService')">
            <h4>加载WMTS服务</h4>
            <svg class="toggle-icon" :class="{ expanded: panelSectionStates.wmtsService }" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="6 9 12 15 18 9"></polyline>
            </svg>
          </div>
          <div class="tech-input-group">
            <input
              v-model="wmtsXmlUrl"
              type="text"
              placeholder="输入WMTS XML URL"
              class="tech-input"
              @keyup.enter="loadWMTSLayer"
            >
            <button
              class="tech-load-btn"
              @click="loadWMTSLayer"
              :disabled="isLoadingWMTS || !wmtsXmlUrl.trim()"
            >
              {{ isLoadingWMTS ? '加载中...' : '加载' }}
            </button>
          </div>
          <div v-if="wmtsLoadStatus" class="tech-status-message">
            {{ wmtsLoadStatus }}
          </div>
          
          <!-- 已加载的WMS/WMTS图层列表 -->
          <div v-if="loadedWmsWmtsLayers.length > 0" class="tech-layer-list">
            <h5>已加载图层</h5>
            <div v-for="layer in loadedWmsWmtsLayers" :key="layer.id" class="tech-layer-item">
              <span>{{ layer.name }}</span>
              <button class="tech-remove-btn" @click="removeWmsWmtsLayer(layer.id)">移除</button>
            </div>
          </div>
        </div>
        
        <!-- 雷达扫描示例 -->
        <div class="panel-section" :data-collapsed="!panelSectionStates.radarScan">
          <div class="panel-section-header" @click="toggleSection('radarScan')">
            <h4>雷达扫描示例</h4>
            <svg class="toggle-icon" :class="{ expanded: panelSectionStates.radarScan }" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="6 9 12 15 18 9"></polyline>
            </svg>
          </div>
          <label class="tech-checkbox">
            <input 
              type="checkbox" 
              v-model="radarEnabled"
              @change="toggleRadar"
            >
            <span class="checkmark"></span>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
              <path d="M12 3v18M3 12h18M12 12l3 3M12 9l-3 3M9 12l3-3M15 12l-3-3"/>
            </svg>
            启用雷达扫描
          </label>
          
          <div v-if="radarEnabled" class="tech-control-group">
            <label class="tech-control-label">
              扫描半径: {{ radarRange }}米
            </label>
            <input
              type="range"
              v-model.number="radarRange"
              min="1000"
              max="20000"
              step="500"
              class="tech-slider"
              @change="radarEnabled && (removeRadar(), createRadar())"
            >
            
            <div class="tech-button-group" style="margin-top: 10px;">
              <div class="tech-btn" @click="flyToRadarPosition">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                  <path d="M12 8v4l3 3"/>
                </svg>
                定位到雷达
              </div>
            </div>
          </div>
        </div>
        
        <!-- 3D Tiles测试 -->
        <div class="panel-section" :data-collapsed="!panelSectionStates.threeDTiles">
          <div class="panel-section-header" @click="toggleSection('threeDTiles')">
            <h4>3D Tiles测试</h4>
            <svg class="toggle-icon" :class="{ expanded: panelSectionStates.threeDTiles }" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="6 9 12 15 18 9"></polyline>
            </svg>
          </div>
          <div class="tech-input-group">
            <input
              v-model="threeDTilesUrl"
              type="text"
              placeholder="输入3D Tiles URL"
              class="tech-input"
              @keyup.enter="testThreeDTiles"
            >
            <button
              class="tech-load-btn"
              @click="testThreeDTiles"
              :disabled="isLoadingThreeDTiles || !threeDTilesUrl.trim()"
            >
              {{ isLoadingThreeDTiles ? '测试中...' : '测试' }}
            </button>
          </div>
          <div v-if="threeDTilesStatus" class="tech-status-message">
            {{ threeDTilesStatus }}
          </div>
          
        </div>

        <!-- 3D Tiles操作按钮 -->
        <div v-if="currentThreeDTilesetId" class="tech-button-group">
            <div class="tech-btn" @click="setThreeDTilesetStyle('height')">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M3 3v18h18M18 17L12 5M6 8l6 12"/>
              </svg>
              高度着色
            </div>
            <div class="tech-btn" @click="setThreeDTilesetStyle('default')">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
              </svg>
              默认样式
            </div>
            <div class="tech-btn" @click="flyToLoadedThreeDTileset">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                <path d="M12 8v4l3 3"/>
              </svg>
              定位到模型
            </div>
            <div class="tech-btn" @click="removeThreeDTileset">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M18 6L6 18M6 6l12 12"/>
              </svg>
              移除模型
            </div>
            <div class="tech-btn" @click="toggleThreeDTilesClampToGround">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/>
                <polyline points="9 22 9 12 15 12 15 22"/>
              </svg>
              {{ isThreeDTilesClampToGround ? '取消贴地' : '贴地显示' }}
            </div>
          </div>
          
          <!-- 贴地相关控制 -->
          <div v-if="currentThreeDTilesetId" class="tech-control-group">
            <label class="tech-control-label">
              高度偏移: {{ threeDTilesHeightOffset }}米
            </label>
            <input
              type="range"
              v-model="threeDTilesHeightOffset"
              min="-10"
              max="10"
              step="0.1"
              class="tech-slider"
              @change="updateThreeDTilesHeightOffset"
            >
          </div>
        </div>
      </div>

    <!-- 自定义标绘组件 -->
    <PlottingComponent v-if="mapUtils && mapUtils.viewer" :viewer="mapUtils.viewer" />
    
    <!-- 自定义弹窗组件 非渲染组件，主要通过JS API使用-->
    <CustomPopup 
      ref="popupComponentRef"
      v-if="true"
      :position="[116.3974, 39.9093, 0]"
      :html="''"
    />
    
    <!-- 坡度坡向分析组件 -->
    <SlopeAspectAnalysis v-if="mapUtils && mapUtils.viewer" :viewer="mapUtils.viewer" />
    <!-- 淹没分析组件 -->
        <SubmergenceAnalysisComponent 
        v-if="mapUtils && mapUtils.viewer"
        :mapUtils="mapUtils"
        @analysis-start="handleAnalysisStart"
        @analysis-stop="handleAnalysisStop"
        @analysis-reset="handleAnalysisReset"
        @analysis-complete="handleAnalysisComplete"
        @status-change="handleAnalysisStatusChange"
        @area-change="handleAnalysisAreaChange"
      />
      <!-- 模拟飞行组件 -->
      <FlightSimulation v-if="mapUtils && mapUtils.viewer" :viewer="mapUtils.viewer" />
      
      <!-- 北斗网格码组件 -->
      <BeidouGridComponent v-if="mapUtils && mapUtils.viewer" :viewer="mapUtils.viewer" />
      
      <!-- 台风组件 -->
      <TyphoonComponent v-if="mapUtils && mapUtils.viewer" :viewer="mapUtils.viewer" />
      
      <!-- 卫星云图组件 -->
      <SatelliteCloudComponent v-if="mapUtils && mapUtils.viewer" :viewer="mapUtils.viewer" />
      
      <!-- CZML展示组件 -->
      <CZMLViewerComponent v-if="mapUtils && mapUtils.viewer" :viewer="mapUtils.viewer" />
  </div>
</template>

<script setup>
import PlottingComponent from './PlottingComponent.vue'
import CustomPopup from './CustomPopup.vue'
import SlopeAspectAnalysis from './SlopeAspectAnalysis.vue'
import MapUtils from '../utils/MapUtils.js'
import TrackMatte from '../utils/TrackMatte .js'
import SubmergenceAnalysisComponent from './SubmergenceAnalysis.vue'
import FlightSimulation from './FlightSimulation.vue'
import BeidouGridComponent from './BeidouGridComponent.vue'
import TyphoonComponent from './TyphoonComponent.vue'
import SatelliteCloudComponent from './SatelliteCloudComponent.vue'
import CZMLViewerComponent from './CZMLViewerComponent.vue'
import { onMounted, ref, onBeforeUnmount } from 'vue';
import '../assets/style/cesium-viewer.css'
 
const mapUtils = ref(null)
const currentBasemap = ref('')
const annotationLayerVisible = ref(true)
const terrainEnabled = ref(false)
const isPanelExpanded = ref(false)
const scgisLayerVisible = ref(false)

// 控制面板折叠状态管理
const panelSectionStates = ref({
  basemap: true,      // 底图类型面板
  layerManagement: true, // 图层管理面板
  wmtsService: true,  // WMTS服务加载面板
  radarScan: true,    // 雷达扫描示例面板
  threeDTiles: true   // 3D Tiles测试面板
})
// WMS/WMTS相关状态
const wmtsXmlUrl = ref('')
const isLoadingWMTS = ref(false)
const wmtsLoadStatus = ref('')
const loadedWmsWmtsLayers = ref([])

// 3D Tiles测试相关状态
const threeDTilesUrl = ref('https://www.scgis.net/services/yibinbuilding/file/tileset.json?ak=eb270c0127fpuolun7b36f27a1ba556d')
const isLoadingThreeDTiles = ref(false)
const threeDTilesStatus = ref('')
const loadedThreeDTilesets = ref([])
const isThreeDTilesClampToGround = ref(false)

// 淹没分析功能已移至独立组件 SubmergenceAnalysisComponent
    
    // 淹没分析事件处理方法
    const handleAnalysisStart = (params) => {
      console.log('淹没分析开始:', params)
      // 可以在这里添加全局状态更新或其他逻辑
    }
    
    const handleAnalysisStop = () => {
      console.log('淹没分析停止')
      // 可以在这里添加全局状态更新或其他逻辑
    }
    
    const handleAnalysisReset = () => {
      console.log('淹没分析重置')
      // 可以在这里添加全局状态更新或其他逻辑
    }
    
    const handleAnalysisComplete = () => {
      console.log('淹没分析完成')
      // 可以在这里添加全局状态更新或其他逻辑
    }
    
    const handleAnalysisStatusChange = (status) => {
      console.log('淹没分析状态变更:', status)
      // 可以在这里更新全局状态或显示通知
    }
    
    const handleAnalysisAreaChange = (area) => {
      console.log('淹没分析区域变更:', area)
      // 可以在这里记录当前选中的区域或其他逻辑
    }
const threeDTilesHeightOffset = ref(0)
let currentThreeDTilesetId = null

// 自定义弹窗实例引用
const popupComponentRef = ref(null)
let popupInstance = null

// 雷达扫描相关状态
const radarEnabled = ref(false)
const radarPosition = ref([116.397428, 39.90923]) // 北京坐标示例
const radarRange = ref(5000) // 默认5公里半径
let radarInstance = null
let radarDemoTimer = null

const togglePanel = () => {
  isPanelExpanded.value = !isPanelExpanded.value
}

// 切换面板展开/折叠状态
const toggleSection = (sectionName) => {
  if (panelSectionStates.value.hasOwnProperty(sectionName)) {
    panelSectionStates.value[sectionName] = !panelSectionStates.value[sectionName]
  }
}

// 底图配置
const basemapConfig = [
  { id: 'img', name: '影像底图' },
  { id: 'vec', name: '矢量底图' },
  { id: 'ter', name: '地形底图' }
]

const switchBasemap = (type) => {
  if (!mapUtils.value) return
  
  currentBasemap.value = type
  mapUtils.value.switchBasemap(type, annotationLayerVisible.value, scgisLayerVisible.value)
}

// 切换SCGIS图层显示/隐藏
const toggleScgisLayer = () => {
  if (!mapUtils.value) return
  
  const success = mapUtils.value.toggleScgisLayer(scgisLayerVisible.value, 1, 0)
  if (!success && scgisLayerVisible.value) {
    scgisLayerVisible.value = false
    alert('加载SCGIS图层失败，请检查网络连接或稍后重试')
  }
}

const toggleAnnotationLayer = () => {
  if (!mapUtils.value) return
  
  mapUtils.value.toggleAnnotationLayer(annotationLayerVisible.value)
}

const toggleTerrain = async () => {
  if (!mapUtils.value) return
  
  const success = await mapUtils.value.toggleTerrain(terrainEnabled.value)
  if (!success) {
    terrainEnabled.value = false
    alert('地形操作失败，请稍后重试')
  }
}

onMounted(async () => {
  // 确保DOM已经渲染完成，并且容器有正确的尺寸
  setTimeout(async () => {
    try {
      // 初始化地图工具类
      mapUtils.value = new MapUtils('cesiumContainer', {
        tiandituToken: '9fd6d5d2f4bebb703692deb3bc0a5da7'
      })
      
      // 初始化Cesium Viewer
      await mapUtils.value.initViewer()

      switchBasemap('img')

      // 添加注记图层
      annotationLayerVisible.value = true
      mapUtils.value.toggleAnnotationLayer(true)
      
      // 使用自定义弹窗组件
      setTimeout(() => {
        if (popupComponentRef.value) {
          try {
            // 创建HTML内容
            const popupHtml = `
              <div style="width: 100%; height: 100%; font-size: 14px; color: blue; padding: 10px;">
                <h3 style="margin-top: 0;">自定义弹窗</h3>
                <p>这是一个使用自定义CustomPopup组件创建的弹窗示例</p>
                <ul style="text-align: left; padding-left: 20px;">
                  <li>可自定义HTML内容</li>
                  <li>支持各种配置选项</li>
                  <li>可添加事件监听</li>
                </ul>
                <button id="popup-btn" style="margin-top: 10px; padding: 5px 10px;">点击我</button>
              </div>
            `
            
            // 获取弹窗方法并添加到viewer
            popupInstance = popupComponentRef.value
            popupInstance.addTo(mapUtils.value.viewer)
            
            // 更新弹窗内容
            popupInstance.updateHtml(popupHtml)
            
            // 添加点击事件监听
            popupInstance.onClickPopup((e) => {
              if (e.target.id === 'popup-btn') {
                alert('点击了弹窗按钮！')
              }
            })
            
            // 添加关闭事件监听
            popupInstance.onClosePopup(() => {
              console.log('弹窗已关闭')
              popupInstance = null
            })
            
          } catch (error) {
            console.error('Error creating custom popup:', error)
          }
        }
      }, 10000)
    } catch (error) {
      console.error('Error initializing map:', error)
    }
  }, 100)
})

// 加载WMTS图层
const loadWMTSLayer = async () => {
  if (!mapUtils.value || !wmtsXmlUrl.value.trim()) {
    wmtsLoadStatus.value = '请输入有效的WMTS XML URL'
    setTimeout(() => {
      wmtsLoadStatus.value = ''
    }, 3000)
    return
  }
  
  isLoadingWMTS.value = true
  wmtsLoadStatus.value = '正在加载WMTS服务...'
  
  try {
    const layerIds = await mapUtils.value.loadWMTSFromUrl(wmtsXmlUrl.value.trim(), {
      alpha: 0.9,
      zIndex: 5,
      flyTo: true
    })
    
    // 更新已加载图层列表
    updateLoadedLayersList()
    
    wmtsLoadStatus.value = `成功加载${layerIds.length}个图层`
    setTimeout(() => {
      wmtsLoadStatus.value = ''
    }, 3000)
  } catch (error) {
    console.error('加载WMTS图层失败:', error)
    wmtsLoadStatus.value = `加载失败: ${error.message}`
    setTimeout(() => {
      wmtsLoadStatus.value = ''
    }, 3000)
  } finally {
    isLoadingWMTS.value = false
  }
}

// 移除WMS/WMTS图层
const removeWmsWmtsLayer = (layerId) => {
  if (!mapUtils.value) return
  
  try {
    const success = mapUtils.value.removeLayer(layerId)
    if (success) {
      // 更新已加载图层列表
      updateLoadedLayersList()
      wmtsLoadStatus.value = '图层已移除'
      setTimeout(() => {
        wmtsLoadStatus.value = ''
      }, 3000)
    }
  } catch (error) {
    console.error('移除图层失败:', error)
  }
}

// 更新已加载图层列表
  const updateLoadedLayersList = () => {
    if (!mapUtils.value) return
    
    try {
      loadedWmsWmtsLayers.value = mapUtils.value.getLoadedLayers()
    } catch (error) {
      console.error('更新图层列表失败:', error)
    }
  }
  
  // 测试3D Tiles图层
  const testThreeDTiles = async () => {
    if (!mapUtils.value || !threeDTilesUrl.value.trim()) {
      threeDTilesStatus.value = '请输入有效的3D Tiles URL'
      setTimeout(() => {
        threeDTilesStatus.value = ''
      }, 3000)
      return
    }
    
    isLoadingThreeDTiles.value = true
    threeDTilesStatus.value = '正在加载3D Tiles数据...'
    
    try {
      // 如果已有加载的3D Tileset，先移除
      if (currentThreeDTilesetId) {
        removeThreeDTileset()
      }
      
      // 加载3D Tiles数据集，设置默认贴地状态
      currentThreeDTilesetId = await mapUtils.value.load3DTileset(threeDTilesUrl.value.trim(), {
        name: '宜宾建筑模型',
        maximumScreenSpaceError: 1,
        flyTo: true,
        clampToGround: isThreeDTilesClampToGround.value,
        heightOffset: threeDTilesHeightOffset.value
      })
      
      // 更新已加载的3D Tileset列表
      updateLoadedThreeDTilesetsList()
      
      threeDTilesStatus.value = '成功加载3D Tiles数据'
      setTimeout(() => {
        threeDTilesStatus.value = ''
      }, 3000)
    } catch (error) {
      console.error('加载3D Tiles数据失败:', error)
      threeDTilesStatus.value = `加载失败: ${error.message}`
      setTimeout(() => {
        threeDTilesStatus.value = ''
      }, 3000)
    } finally {
      isLoadingThreeDTiles.value = false
    }
  }
  
  // 设置3D Tiles样式
  const setThreeDTilesetStyle = (styleType) => {
    if (!mapUtils.value || !currentThreeDTilesetId) {
      return
    }
    
    try {
      if (styleType === 'height') {
        // 创建基于高度的样式
        const heightStyle = mapUtils.value.createHeightBased3DTilesStyle([
          [100, 'red'],
          [50, 'orange'],
          [20, 'yellow'],
          [0, 'green']
        ], 'color(\'blue\')')
        mapUtils.value.set3DTilesetStyle(currentThreeDTilesetId, heightStyle)
        threeDTilesStatus.value = '已应用高度着色样式'
      } else {
        // 恢复默认样式
        mapUtils.value.set3DTilesetStyle(currentThreeDTilesetId, '')
      }
      
      setTimeout(() => {
        threeDTilesStatus.value = ''
      }, 3000)
    } catch (error) {
      console.error('设置3D Tiles样式失败:', error)
      threeDTilesStatus.value = `样式设置失败: ${error.message}`
      setTimeout(() => {
        threeDTilesStatus.value = ''
      }, 3000)
    }
  }
  
  // 定位到已加载的3D Tileset
  const flyToLoadedThreeDTileset = () => {
    if (!mapUtils.value || !currentThreeDTilesetId) {
      return
    }
    
    try {
      mapUtils.value.flyTo3DTileset(currentThreeDTilesetId, {
        duration: 2,
        offset: 1500
      })
    } catch (error) {
      console.error('定位到3D Tiles失败:', error)
    }
  }
  
  // 移除3D Tileset
  const removeThreeDTileset = () => {
    if (!mapUtils.value || !currentThreeDTilesetId) {
      return
    }
    
    try {
      mapUtils.value.remove3DTileset(currentThreeDTilesetId)
      currentThreeDTilesetId = null
      updateLoadedThreeDTilesetsList()
      threeDTilesStatus.value = '已移除3D Tiles数据'
      setTimeout(() => {
        threeDTilesStatus.value = ''
      }, 3000)
    } catch (error) {
      console.error('移除3D Tiles失败:', error)
      threeDTilesStatus.value = `移除失败: ${error.message}`
      setTimeout(() => {
        threeDTilesStatus.value = ''
      }, 3000)
    }
  }
  
  // 更新已加载的3D Tileset列表
  const updateLoadedThreeDTilesetsList = () => {
    if (!mapUtils.value) return
    
    try {
      loadedThreeDTilesets.value = mapUtils.value.getLoaded3DTilesets()
    } catch (error) {
      console.error('更新3D Tiles列表失败:', error)
    }
  }
  
  // 切换3D Tiles贴地状态
  const toggleThreeDTilesClampToGround = () => {
    if (!mapUtils.value || !currentThreeDTilesetId) {
      return
    }
    
    try {
      isThreeDTilesClampToGround.value = !isThreeDTilesClampToGround.value
      const success = mapUtils.value.set3DTilesetClampToGround(
        currentThreeDTilesetId,
        isThreeDTilesClampToGround.value,
        threeDTilesHeightOffset.value
      )
      
      if (success) {
        threeDTilesStatus.value = isThreeDTilesClampToGround.value ? '已开启贴地显示' : '已取消贴地显示'
        setTimeout(() => {
          threeDTilesStatus.value = ''
        }, 3000)
      } else {
        threeDTilesStatus.value = '操作失败，请稍后重试'
        setTimeout(() => {
          threeDTilesStatus.value = ''
        }, 3000)
      }
    } catch (error) {
      console.error('切换3D Tiles贴地状态失败:', error)
      threeDTilesStatus.value = `操作失败: ${error.message}`
      setTimeout(() => {
        threeDTilesStatus.value = ''
      }, 3000)
    }
  }
  
  // 更新3D Tiles高度偏移
  const updateThreeDTilesHeightOffset = () => {
    if (!mapUtils.value || !currentThreeDTilesetId) {
      return
    }
    
    try {
      const success = mapUtils.value.set3DTilesetClampToGround(
        currentThreeDTilesetId,
        isThreeDTilesClampToGround.value,
        threeDTilesHeightOffset.value
      )
      
      if (success) {
        threeDTilesStatus.value = `已设置高度偏移为${threeDTilesHeightOffset.value}米`
        setTimeout(() => {
          threeDTilesStatus.value = ''
        }, 3000)
      }
    } catch (error) {
      console.error('更新3D Tiles高度偏移失败:', error)
      threeDTilesStatus.value = `操作失败: ${error.message}`
      setTimeout(() => {
        threeDTilesStatus.value = ''
      }, 3000)
    }
  }

// 创建雷达扫描实例
  const createRadar = () => {
    if (!mapUtils.value || !mapUtils.value.viewer || radarInstance) return
    
    try {
      // 创建雷达实例
      radarInstance = new TrackMatte({
        viewer: mapUtils.value.viewer,
        id: 'demoRadar',
        position: radarPosition.value,
        shortwaveRange: radarRange.value
      })
      radarEnabled.value = true
    } catch (error) {
      console.error('创建雷达扫描失败:', error)
    }
  }
  
  // 移除雷达扫描实例
  const removeRadar = () => {
    if (!mapUtils.value.viewer || !radarInstance) return
    
    try {
      mapUtils.value.viewer.entities.removeById('demoRadar')
      radarInstance = null
      radarEnabled.value = false
    } catch (error) {
      console.error('移除雷达扫描失败:', error)
    }
  }
  
  // 切换雷达扫描显示状态
  const toggleRadar = () => {
    if (!radarEnabled.value) {
      removeRadar()
    } else {
      createRadar()
    }
  }
  
  // 定位到雷达位置
  const flyToRadarPosition = () => {
    if (!mapUtils || !mapUtils.value.viewer) return
    
    try {
      // 通过mapUtils获取Cesium实例
      const Cesium = mapUtils.value.customCesium;
      mapUtils.value.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          radarPosition.value[0],
          radarPosition.value[1],
          radarRange.value * 2
        ),
        duration: 3
      })
    } catch (error) {
      console.error('定位到雷达位置失败:', error)
    }
  }
  
  // 组件卸载时清理资源
  onBeforeUnmount(() => {
    // 销毁自定义弹窗
    if (popupInstance) {
      popupInstance.destroy()
      popupInstance = null
    }
    
    // 销毁雷达扫描实例
    if (radarDemoTimer) {
      clearTimeout(radarDemoTimer)
      radarDemoTimer = null
    }
    
    // 淹没分析实例清理已由SubmergenceAnalysis组件内部处理
    
    // 销毁地图工具实例
    if (mapUtils.value) {
      mapUtils.value.destroy()
    }
  })
</script>

<!-- 样式已抽取到外部CSS文件: ../assets/style/cesium-viewer.css -->